<template>
  <div class="tag-container">
    <div style="display: flex;gap:5px;align-items: center;">
      <el-switch v-model="useCombinedPrompt"></el-switch>
      <el-popover placement="top" :width="470" trigger="hover">
        <template #reference>
          <el-button size="default" class="range-btn" type="primary">{{ state.value}}</el-button>
        </template>
        <div>
          <el-slider style="width:400px;margin-left: 20px;" :step="0.5" v-model="state.value" range
            show-stops :min="0" :max="10" />
        </div>
      </el-popover>
      <el-select
        size="default"
        v-model="state.type"
        :placeholder="$t('message.random.selectClassType')"
      >
        <el-option
          v-for="item in state.classType"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button size="default" type="primary" @click="getCommonRandom">
        {{ $t('message.random.random') }}
      </el-button>
      <el-select
        size="default"
        v-model="state.selectedConfigId"
        @change="handleConfigSelect"
        :placeholder="$t('message.random.selectPreset')"
        class="mr10"
      >
        <el-option
          v-for="config in state.customConfigs"
          :key="config.id"
          :label="config.name"
          :value="config.id"
        />
      </el-select>
      <el-button size="default"
          type="success"
          icon="MagicStick"
          @click="generateTags"
        >{{ $t('message.random.generateTags') }}</el-button>
    </div>
    <div class="tags-display">
      <div class="tags-flow">
        <div
          v-for="(tag, index) in tagList"
          :key="tag + index"
          class="tag-card"
          :style="{
            height: `${tagHeight}px`,
            '--hue': (index * 37) % 360
          }"
        >
          <el-popover
            :width="280"
            placement="bottom"
            trigger="click"
            @hide="handlePopoverHide(tag)"
          >
            <template #reference>
              <div class="tag-content">
                <div class="tag-english">{{ tag }}</div>
                <div class="tag-chinese">
                  <template v-if="translationStatus[tag] === 'loading'">
                    <span class="loading-indicator">
                      <div class="loading-dot"></div>
                      <div class="loading-dot"></div>
                      <div class="loading-dot"></div>
                    </span>
                  </template>
                  <template v-else>
                    {{ translatedTags[tag] || tag }}
                    <!-- 显示当前权重 -->
                    <span v-if="tagWeights[tag] !== 1" class="weight-badge">
                      {{ tagWeights[tag] }}
                    </span>
                  </template>
                </div>
              </div>
            </template>

            <!-- Popover内容：权重编辑 -->
            <div class="weight-editor">
              <div class="editor-header">
                <span>{{ tag }}</span>
                <el-button
                  size="default"
                  type="danger"
                  @click="removeTag(index)"
                >移除</el-button>
              </div>

              <div class="weight-control">
                <span class="weight-label">权重:</span>
                <el-slider
                  v-model="tagWeights[tag]"
                  :min="0.5"
                  :max="2"
                  :step="0.1"
                  show-input
                  input-size="default"
                  :format-tooltip="formatWeight"
                  @input="debouncedApplyWeightChange(tag)"
                />
              </div>

              <div class="weight-actions">
                <el-button
                  size="default"
                  @click="resetWeight(tag)"
                >重置</el-button>
              </div>
            </div>
          </el-popover>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, reactive, shallowRef } from 'vue';
import { useGenerationStore } from '@renderer/stores/useGenerationStore';
import { translateApi } from '@renderer/api/translate';
import { commonApi } from '@renderer/api/common';
import { tagApi } from '@renderer/api/tags';
import { ElMessage } from 'element-plus';
import debounce from 'lodash/debounce';

const generationStore = useGenerationStore();
const tagHeight = ref(60);
const translatedTags = ref<Record<string, string>>({});
const translationStatus = ref<Record<string, 'idle' | 'loading' | 'loaded' | 'error'>>({});
let translationQueue: string[] = [];
let translationTimer: ReturnType<typeof setTimeout> | null = null;

const hitCountQueue = ref<Set<string>>(new Set());
let hitCountTimer: ReturnType<typeof setTimeout> | null = null;
const HIT_COUNT_BATCH_SIZE = 20;
const HIT_COUNT_DEBOUNCE = 10000;
const useCombinedPrompt = ref(false);
const tagList = shallowRef<string[]>([]);
const promptSource = computed(() =>
  useCombinedPrompt.value
    ? generationStore.combinedPrompt
    : generationStore.params.prompt
);

// 标签权重相关
const tagWeights = ref<Record<string, number>>({});
const activePopoverTag = ref<string | null>(null);

// 权重应用防抖函数
const debouncedApplyWeightChange = debounce((tag: string) => {
  //applyWeightChange(tag);
}, 500);

// 格式化权重显示
const formatWeight = (value: number) => {
  return value === 1 ? '正常' : value.toFixed(1);
};

// 重置权重
const resetWeight = (tag: string) => {
  tagWeights.value[tag] = 1.0;
  applyWeightChange(tag);
};

// 简化的权重解析函数
const parseTagWeight = (tag: string): number => {
  // 匹配标签末尾的权重标记（格式如 :1.2, :0.9, :1.5) 等）
  const weightMatch = tag.match(/:([\d.]+)\)?$/);
  if (weightMatch && weightMatch[1]) {
    return parseFloat(weightMatch[1]);
  }
  return 1.0;
};

// 提取标签纯文本（移除权重和括号）
const extractPureTag = (tag: string): string => {
  // 移除尾部权重部分（如果存在）
  const withoutWeight = tag.replace(/:[\d.]+\)?$/, '');

  // 移除外层括号（如果有）
  return withoutWeight
    .replace(/^\(/, '')
    .replace(/\)$/, '')
    .replace(/^\{/, '')
    .replace(/\}$/, '')
    .replace(/^\[/, '')
    .replace(/\]$/, '')
    .replace(/^\{\{/, '')
    .replace(/\}\}$/, '')
    .trim();
};

// 应用权重变更
const applyWeightChange = (tag: string) => {
  const weight = tagWeights.value[tag];
  const pureTag = extractPureTag(tag);

  // 1. 获取当前提示词
  let currentPrompt = generationStore.params.prompt;

  // 2. 创建标签匹配正则（考虑可能存在的权重标记）
  const escapedTag = escapeRegExp(tag);
  const tagRegex = new RegExp(escapedTag, 'g');

  // 3. 替换标签
  let newPrompt = currentPrompt;
  let tagFound = false;

  newPrompt = newPrompt.replace(tagRegex, () => {
    tagFound = true;

    if (weight === 1) {
      // 权重为1时返回纯标签
      return pureTag;
    } else {
      // 否则返回带权重的标签格式
      return `(${pureTag}:${weight.toFixed(1)})`;
    }
  });

  // 4. 更新提示词
  if (tagFound) {
    generationStore.params.prompt = newPrompt;
  }
};

// 移除标签
const removeTag = (index: number) => {
  const tagToRemove = tagList.value[index];

  // 创建标签匹配正则
  const escapedTag = escapeRegExp(tagToRemove);
  const tagRegex = new RegExp(escapedTag, 'g');

  // 替换标签（包括前后逗号）
  generationStore.params.prompt = generationStore.params.prompt
    .replace(tagRegex, '') // 移除标签
    .replace(/,{2,}/g, ',') // 清理多余逗号
    .replace(/^,|,$/g, '') // 清理开头结尾逗号
    .trim();

  // 清理权重记录
  delete tagWeights.value[tagToRemove];
};

// 辅助函数：转义正则特殊字符
const escapeRegExp = (string: string) => {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};

// Popover关闭时处理
const handlePopoverHide = (tag: string) => {
  applyWeightChange(tag);
  activePopoverTag.value = null;
};

const parseTagsDebounced = debounce(() => {
  if (!promptSource.value) {
    tagList.value = [];
    return;
  }

  // 1. 使用逗号分割提示词
  const rawTags = promptSource.value
    .split(',')
    .map(tag => tag.trim())
    .filter(tag => tag.length > 0);

  // 2. 存储原始标签（包含权重和括号）
  tagList.value = rawTags;

  // 3. 初始化权重
  rawTags.forEach(tag => {
    tagWeights.value[tag] = parseTagWeight(tag);
  });
}, 300);

// 监听提示源变化
watch(promptSource, () => {
  parseTagsDebounced();
}, { immediate: true });

// 监听标签列表变化
watch(tagList, (newTags) => {
  // 清理不存在的标签权重
  Object.keys(tagWeights.value).forEach(tag => {
    if (!newTags.includes(tag)) {
      delete tagWeights.value[tag];
    }
  });
}, { immediate: true, deep: true });

// 处理标签翻译（核心优化）
const processTranslationQueue = async () => {
  if (translationQueue.length === 0) return;

  // 提取纯标签文本（不含权重和括号）
  const pureTags = translationQueue.map(extractPureTag);
  const uniquePureTags = [...new Set(pureTags)];

  // 清理翻译队列
  translationQueue = [];

  // 设置加载状态
  uniquePureTags.forEach(tag => {
    translationStatus.value[tag] = 'loading';
  });

  try {
    const response = await translateApi().translateTags({ tags: uniquePureTags });
    const translations = response.data.translations;

    // 处理翻译结果
    uniquePureTags.forEach(pureTag => {
      if (translations[pureTag]) {
        // 将翻译结果映射回原始标签
        tagList.value.forEach(rawTag => {
          if (extractPureTag(rawTag) === pureTag) {
            translatedTags.value[rawTag] = translations[pureTag];
          }
        });

        translationStatus.value[pureTag] = 'loaded';
        hitCountQueue.value.add(pureTag);
        scheduleHitCountUpdate();
      } else {
        translationStatus.value[pureTag] = 'idle';
      }
    });
  } catch (error) {
    console.error('翻译请求失败:', error);
    uniquePureTags.forEach(tag => {
      translationStatus.value[tag] = 'error';
    });
  }
};

// 添加标签到翻译队列
const queueTagForTranslation = (tag: string) => {
  const pureTag = extractPureTag(tag);

  if (
    translationStatus.value[pureTag] === 'loading' ||
    translationStatus.value[pureTag] === 'loaded'
  ) return;

  if (!translationStatus.value[pureTag]) {
    translationStatus.value[pureTag] = 'idle';
  }

  if (!translationQueue.includes(tag)) {
    translationQueue.push(tag);
  }

  if (translationTimer) clearTimeout(translationTimer);
  translationTimer = setTimeout(() => {
    processTranslationQueue();
    translationTimer = null;
  }, 300);
};

// 监听标签列表变化
watch(tagList, (newTags) => {
  // 清理不存在的翻译状态
  Object.keys(translationStatus.value).forEach(tag => {
    const exists = newTags.some(rawTag => extractPureTag(rawTag) === tag);
    if (!exists) {
      delete translationStatus.value[tag];
      delete translatedTags.value[tag];
    }
  });

  // 添加新标签到翻译队列
  newTags.forEach(tag => {
    queueTagForTranslation(tag);
  });
}, { immediate: true });

// 调度命中计数更新
const scheduleHitCountUpdate = () => {
  if (hitCountQueue.value.size >= HIT_COUNT_BATCH_SIZE) {
    sendHitCountUpdate();
    return;
  }

  if (hitCountTimer) clearTimeout(hitCountTimer);
  hitCountTimer = setTimeout(() => {
    if (hitCountQueue.value.size > 0) {
      sendHitCountUpdate();
    }
    hitCountTimer = null;
  }, HIT_COUNT_DEBOUNCE);
};

// 发送命中计数更新请求
const sendHitCountUpdate = async () => {
  if (hitCountQueue.value.size === 0) return;

  const tagsToUpdate = [...hitCountQueue.value];
  hitCountQueue.value.clear();

  try {
    await translateApi().updateHitCount({
      tags: tagsToUpdate
    });
    console.log(`成功更新 ${tagsToUpdate.length} 个标签的命中计数`);
  } catch (error) {
    console.error('命中计数更新失败:', error);
    tagsToUpdate.forEach(tag => hitCountQueue.value.add(tag));
    scheduleHitCountUpdate();
  }
};

// 监听标签列表变化
watch(tagList, (newTags) => {
  Object.keys(translationStatus.value).forEach(tag => {
    if (!newTags.includes(tag)) {
      delete translationStatus.value[tag];
      delete translatedTags.value[tag];
    }
  });

  newTags.forEach(tag => {
    queueTagForTranslation(tag);
  });
}, { immediate: true });

interface CustomConfig {
  id: string
  name: string
  conditions: Condition[]
  createTime: number
}

interface Condition {
  path: string[]
  group: string
  name?: string | null;
  size: number
  locked?: boolean
  currentTags?: Array<{ value: string; label: string }>
}

//随机部分
const state = reactive({
  value: [0,0],
  type: 'collect',
  classType:[
    {label:'收藏',value:'collect'},
    {label:'风格',value:'style'},
    {label:'动作',value:'action'},
    {label:'服装',value:'cloth'},
    {label:'预设',value:'preset'},
    {label:'反向',value:'negative'}
  ],
  selectedConfigId: '',
  customConfigs:[] as CustomConfig[],
  conditions: [] as Condition[],
  loading: false
})

const getCommonRandom = async () => {
  const search = {
    class_type: state.type,
    value: state.value,
  }
  const res = await commonApi().getRandomChioce(search);
  const result = res.data.result;
  const tags = result.tags.split('Negative prompt')[0];
  generationStore.params.prompt += ',' + tags
};

const loadCustomConfigs = async () => {
  try {
    const res = await tagApi().getRandomTagsConfig();
    state.customConfigs = res.data.data;
  } catch (error) {
    ElMessage.error('配置加载失败');
  }
}

const handleConfigSelect = async (configId: string) => {
  try {
    state.conditions = state.customConfigs.find(item => item.id === configId)?.conditions ?? [];
  } catch (error) {
    ElMessage.error('加载配置失败');
  }
}

const generateTags = async () => {
  try {
    state.loading = true;
    if(state.conditions.length == 0){
      ElMessage.error('Config Error')
    }
    else{
      const {data} = await tagApi().batchGenerateTags(state.conditions);
      const combinedValues = data.results.flatMap(result =>
        result.tags.map(tag => tag.value)
      ).join(',');
      generationStore.params.prompt += combinedValues
      }
  }
  catch(error){

  }
}

// 组件挂载时初始化
onMounted(() => {
  loadCustomConfigs();
  tagList.value.forEach(tag => {
    queueTagForTranslation(tag);
  });
});

// 组件卸载前更新剩余计数
onBeforeUnmount(() => {
  if (hitCountQueue.value.size > 0) {
    sendHitCountUpdate();
  }
  if (hitCountTimer) clearTimeout(hitCountTimer);
  if (translationTimer) {
    clearTimeout(translationTimer);
    translationTimer = null;
  }
});
</script>

<style scoped>


.compact-controls {
  background: #ffffff;
  border-radius: 12px;
  padding: 12px 16px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #eaeaea;
}

.size-control {
  display: flex;
  align-items: center;
  gap: 12px;
}

.control-label {
  font-size: 14px;
  font-weight: 500;
  color: #4b5563;
}

.size-value {
  font-weight: 600;
  color: #6366f1;
  min-width: 50px;
  text-align: center;
}

.tags-display {
  background: var(--el-color-white);
  border-radius: 16px;
  padding: 16px;
  border: 1px solid var(--el-border-color);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
}

.tags-flow {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-card {
  --base-color: hsl(var(--hue), 70%, 45%);
  --light-color: hsl(var(--hue), 70%, 95%);

  position: relative;
  display: inline-flex;
  flex-direction: column;
  justify-content: center;
  min-width: 80px;
  padding: 0 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
  background: var(--light-color);
  box-shadow:
    0 2px 6px rgba(0, 0, 0, 0.05),
    inset 0 0 0 1px rgba(0, 0, 0, 0.03);
  overflow: hidden;
  cursor: pointer;
  animation: fadeIn 0.4s ease-out;
}

.tag-card:hover {
  transform: translateY(-2px);
  box-shadow:
    0 4px 10px rgba(0, 0, 0, 0.08),
    inset 0 0 0 1px rgba(0, 0, 0, 0.05);
}

.tag-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: var(--base-color);
}

.tag-content {
  text-align: center;
  padding: 0 4px;
}

.tag-english {
  font-size: calc(v-bind(tagHeight) * 0.25px);
  font-weight: 600;
  color: #1f2937;
  margin-bottom: calc(v-bind(tagHeight) * 0.05px);
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  transition: all 0.2s ease;
}

.tag-chinese {
  font-size: calc(v-bind(tagHeight) * 0.2px);
  color: #4b5563;
  font-weight: 500;
  transition: all 0.2s ease;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .compact-controls {
    padding: 10px 12px;
  }

  .size-control {
    gap: 8px;
  }

  .control-label {
    font-size: 13px;
  }

  :deep(.el-slider) {
    width: 150px;
  }
}

@media (max-width: 480px) {
  .tag-container {
    padding: 12px;
  }

  .tags-display {
    padding: 12px;
  }

  .tag-card {
    min-width: 70px;
    padding: 0 12px;
  }
}

.range-btn{
  min-width: 70px;
}

/* 添加权重编辑相关样式 */

.weight-editor {
  padding: 12px;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.editor-header span {
  font-weight: 600;
  font-size: 14px;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.weight-control {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.weight-label {
  font-size: 13px;
  margin-right: 12px;
  min-width: 40px;
  color: #666;
}

.weight-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.weight-badge {
  display: inline-block;
  margin-left: 5px;
  padding: 1px 5px;
  border-radius: 4px;
  background-color: rgba(99, 102, 241, 0.15);
  color: #6366f1;
  font-size: 10px;
  font-weight: 600;
  line-height: 1;
  transform: translateY(-1px);
}

/* 调整Popover内部滑块样式 */
:deep(.el-slider__input) {
  width: 80px !important;
}
</style>
